/*
 * 通用js
 */

$(document).ready(function () {
    

});

// using jQuery ajax 避免django提交ajax报错403
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // 这些HTTP方法不要求CSRF包含
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

/*
 * 返回上页
 */
function back() {
    history.back(-1);
}

/*
 * 刷新页面
 */
function refresh() {
    window.location.reload();
    return false;
}


/*
 * 勾选全部
 *
 * 复选框
 *
 */
function check_all(obj, id) {
    var flag = $(obj).is(':checked') ? true : false;

    $("tr td input#" + id).each(function () {
        var obj_td = $(this).parent();

        var bg = obj_td.parent().css("background");

        if (!$(this).prop('disabled')) {

            if (flag) {
                $(this).prop('checked', true);
                obj_td.css("background", "#428bca");
            } else {
                $(this).removeAttr("checked"); //移除属性checked
                obj_td.css("background", bg);
            }
        }
    });
}

/*
 * 勾选当前行
 *
 * 复选框
 *
 */
function check_this(obj) {

    var obj_checkbox = $(obj).children().find('input:checkbox');
    var obj_td = obj_checkbox.parent();

    if (obj_td.is('label')) {
        obj_td = obj_checkbox.parent().parent();
    }
    var bg = $(obj).css("background");

    if (obj_checkbox.is(':checked')) {
        obj_checkbox.prop('checked', false);
        obj_td.css("background", bg);
    } else {
        obj_checkbox.prop('checked', true);
        obj_td.css("background", "#428bca");
    }

    // 避免单独点击输入框而无法选中情况
    $('input:checkbox').click(function (event) {
        // 阻止事件冒泡
        event.stopPropagation();
    });
}


/*
 * 跳转页面
 */
function jump(url) {
    window.location = __url(url);
}

/**
 * 弹出消息提示窗口
 **/
function show_message(message, options) {

    var messages = new Array();
    if (typeof message === 'string') {
        messages.push(message);
    } else {
        messages = message;
    }

    var def_option = {
        type: 'message',
        callback: function () {
        },
        autoclose: true,
        verify: {
            open: false,
            orgurl: '',
            verifycode: ''
        }
    };

    var opt = $.extend(def_option, options);
    var data = '<ul>';
    for (i = 0; i < messages.length; i++) {
        data += ('<li' + (opt.type === 'warning' ? ' class="error"' : '') + '>' + messages[i] + '</li>');
    }

    // 自动关闭窗口
    if (opt.autoclose) {
        data += '</ul><em style="font-size: 12px;">将在<span id="second">10</span>秒后自动关闭</em>';
    }

    // 验证码
    if (opt.verify.open) {
        data += '<div class="form-group has-feedback">\n' +
            '   <label><em style="color: red;">*</em>验证码:</label>\n' +
            '   <img id="captcha" src="'+opt.verify.orgurl+'" alt="Captcha"\n' +
            '       style="cursor: pointer;" />\n' +
            '   <input type="text" class="form-control" name="verify_code" value="" />\n' +
            '   <!--删除按钮-->\n' +
            '   <a class="glyphicon glyphicon-remove btn form-control-feedback"\n' +
            '       id="del_text" style="margin-top: 15px;"></a>\n' + opt.verify.verifycode +
            '</div>';
    }

    //判断div是否存在
    var div = $('#div_show_message');
    if (div.length === 0) {
        div = $('<div id="div_show_message" />');
    }

    var buttons = new Array();
    buttons.push({
        text: '确定',
        click: function () {
            opt.callback();
            $(this).dialog('close');
        }
    });

    if (opt.type === 'confirm') {
        buttons.push({
            text: '取消',
            click: function () {
                $(this).dialog('close');
            }
        });
    }

    var title = '';
    if (opt.type === 'warning') {
        title = '警告';
    } else if (opt.type === 'confirm') {
        title = '请确认';
    } else {
        title = '提示消息';
    }

    // 弹出位置选择对话框, 并自动关闭
    var sid = null; // 定义定时器id
    var dg = $(div).html(data).dialog({
        title: title,
        // width: 400,
        resizable: false,
        modal: true,
        buttons: buttons,
        open: function () {
            if (opt.autoclose) {
                var seconds = 10;
                $('#second').text(seconds--);   // 开始前先减1, 避免过长停留在数字10
                sid = setInterval(function () {
                    $('#second').text(seconds--);
                    if (seconds === -1) {   // 设置0, 1会看不到就关闭了
                        dg.dialog('close');
                    }
                }, 1000);
            }

            if (opt.verify.open) {
                // 验证码, 设置随机数, 避免缓存
                $('#captcha').click(function () {
                    this.setAttribute('src',
                        opt.verify.orgurl+'&nocache='+Math.random());
                });
                $('.has-feedback #del_text').click(function () {
                    $(this).parent().children('input[type="text"]').val('');
                });
            }
        },
        close: function () {
            if (opt.autoclose) {
                clearInterval(sid); // 停止定时器
            }
        }
    });
}

// 输入框右侧删除按钮
$('.has-feedback #del_text').click(function () {
    $(this).parent().children('input[type="text"]').val('');
});
